import dayjs from 'dayjs'

export function objectToFormData(obj, formData = new FormData(), parentKey = '') {
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const value = obj[key]
      // 如果value是数组或者对象，需要递归处理
      if (value instanceof Array) {
        value.forEach((item, index) => {
          objectToFormData(item, formData, `${parentKey}${key}[${index}]`)
        })
      } else if (value instanceof Object) {
        objectToFormData(value, formData, parentKey ? `${parentKey}${key}.` : `${key}.`)
      } else {
        // 对于简单类型，直接添加到formData中
        formData.append(`${parentKey}${key}`, value)
      }
    }
  }
  return formData
}

export const generateNowDate = () => {
  const now = dayjs()
  const date = now.format('YYYY-MM-DD')
  return now
}

export const generateNowTime = () => {
  let now = dayjs()
  let time = now.format('HH:mm:ss')
  return now
}

export const generateCheckSerial = () => {
  let now = dayjs()
  let serial = now.format('YYYYMMDDHHmmss')
  return `ELEFLAI${serial}`
}

export function calculateBirthYearMonth(age) {
  const currentDate = dayjs() // 获取当前日期

  const birthDate = currentDate.subtract(age, 'year') // 从当前日期减去指定的年龄

  // 格式化出生年月为 YYYY-MM 格式
  return birthDate.format('YYYY-MM-DD')
}

export function calculateAge(birthDateString) {
  const birthDate = new Date(birthDateString)
  const currentDate = new Date()
  if (birthDate > currentDate) {
    return '输入的出生日期在未来，请重新输入！'
  }
  let age = currentDate.getFullYear() - birthDate.getFullYear()
  const monthDiff = currentDate.getMonth() - birthDate.getMonth()
  // 如果当前月份小于出生月份，或者月份相同但当前日期小于出生日期，则年龄减一
  if (monthDiff < 0 || (monthDiff === 0 && currentDate.getDate() < birthDate.getDate())) {
    age--
  }
  return age
}

export function printFormData(formData,beginString) {
  console.log(beginString)
  let arr = [...formData.keys()]
  arr.forEach((k) => {
    console.log(k, formData.get(k))
  })
  console.log('--------------------')
}

// export const generateNowTime = () => {
//   let now = dayjs()
//   let time = now.format('HH:mm:ss')
//   console.log(dayjs(time, 'HH:mm:ss'))
//   return dayjs(time, 'HH:mm:ss')
// }
